package com.cpr.core.rabbitmq.client;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.nio.charset.StandardCharsets;

/**
 * @author Chen Panrui
 * created at 2022/3/10 13:05
 *
 * PDF:
 * 关于 mandatory: 万一RouteKey没有指定的队列queue，消息会被退还给生产者设置为true，设置为false就会丢掉
 * 关于 immediate: 这个消息需要立刻被消费掉，设置为true
 *
 */
public class HelloProducer {

    public static final String HOST = "106.13.89.7";
    public static final String USER_NAME = "admin";
    public static final String PASSWORD = "123456";
    public static final int PORT = 5672;

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        factory.setPort(PORT);
        factory.setVirtualHost("/");
        //
        factory.setAutomaticRecoveryEnabled(true);

        // 一个TCP连接
        Connection connection = factory.newConnection();
        // 也可以指定channel的编号
        Channel channel = connection.createChannel();

        // 声明一个队列，args:队列名称，是否持久化(重启后是否还在)，是否排他的(是否只能当前连接享受)，是否自动删除，队列的属性信息
        channel.queueDeclare("queue.biz", true, false, false, null);
        // 声明一个交换器，args: 交换器名称，类型，是否持久化，是否是自动删除的，交换器的属性信息
        channel.exchangeDeclare("ex.biz", BuiltinExchangeType.DIRECT, true, false, null);
        // 将交换器和队列绑定，并指定路由键
        channel.queueBind("queue.biz", "ex.biz", "hello.world");
        // 发送消息，args: 交换器名称，路由键，BasicProperties对象，消息字节数组
        channel.basicPublish("ex.biz", "hello.world", null, "chenpanrui".getBytes(StandardCharsets.UTF_8));

        channel.close();
        connection.close();
    }
}
